<?php

namespace DreamCat\FrameCore\Cases\ErrorHandle;

use DreamCat\FrameCore\Factory\Impl\Container\DefaultContainerFactory;
use DreamCat\FrameCore\HttpHandle\DefaultErrorHandle;
use DreamCat\FrameInterface\ConfigReader;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Zend\Diactoros\Response\TextResponse;

/**
 * 默认错误处理测试
 * @author vijay
 */
class DefaultErrorHandleTest extends TestCase
{
    /**
     * 测试 handle 方法
     * @return void
     */
    public function testHandle()
    {
        $configReader = $this->getMockForAbstractClass(ConfigReader::class);
        $configReader->method("get")->willReturnArgument(1);
        $container = (new DefaultContainerFactory())->create($configReader);
        $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class);
        $throwable = new \Exception("测试异常", 400);
        $loggerMock->expects(static::once())
            ->method("error")
            ->with(
                static::equalTo($throwable->getMessage()),
                static::equalTo(
                    [
                        "trace" => $throwable->getTraceAsString(),
                        "file" => $throwable->getFile(),
                        "line" => $throwable->getLine(),
                        "code" => $throwable->getCode(),
                    ]
                )
            );
        /** @var DefaultErrorHandle $handle */
        $handle = $container->get(DefaultErrorHandle::class);
        $errorMsg = uniqid("errorMsg-");
        $handle->setLogger($loggerMock)
            ->setErrorMsg($errorMsg);
        $result = $handle->handle($throwable);
        self::assertEquals(TextResponse::class, get_class($result));
        self::assertEquals(500, $result->getStatusCode());
        self::assertEquals($errorMsg, $result->getBody()->getContents());
    }
}

# end of file
